package libs.yzx.zaza.acts2;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import libs.yzx.zaza.R;

/**
 * Created by yangzhongxu on 16/10/7.
 */

public class DrawableActivity extends AppCompatActivity {

    private Bitmap bmp;
    private View view;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_drawable);
        view = findViewById(R.id.view);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inMutable = true;

        bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.fengjing, options);


        RoundDrawable rd = new RoundDrawable(bmp);

        if (Build.VERSION.SDK_INT < 16)
            view.setBackgroundDrawable(rd);
        else
            view.setBackground(rd);



    }


    public static class RoundDrawable extends Drawable {

        private Bitmap mBmp;
        private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        private BitmapShader bs;
        private RectF rect;

        public RoundDrawable(Bitmap bmp) {
            this.mBmp = bmp;
            bs = new BitmapShader(bmp, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            paint.setDither(true);
            paint.setShader(bs);

        }


        @Override
        public void setAlpha(int i) {
            paint.setAlpha(i);
        }


        @Override
        public void setBounds(Rect bounds) {
            super.setBounds(bounds);
            rect = new RectF(bounds.left, bounds.top, bounds.right, bounds.bottom);
        }

        @Override
        public void setBounds(int left, int top, int right, int bottom) {
            super.setBounds(left, top, right, bottom);
            rect = new RectF(left, top, right, bottom);
        }

        @Override
        public void draw(@NonNull Canvas canvas) {
            canvas.drawRoundRect(rect, 40, 40, paint);
        }


        @Override
        public void setColorFilter(ColorFilter colorFilter) {
            paint.setColorFilter(colorFilter);
        }


        @Override
        public int getOpacity() {
            return PixelFormat.TRANSLUCENT;
        }

        @Override
        public int getIntrinsicHeight() {
            return mBmp.getHeight();
        }

        @Override
        public int getIntrinsicWidth() {
            return mBmp.getWidth();
        }


    }


}
